import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.CountDownLatch;

/**
 * @Version :1.0
 * @PROJECT_NAME: java-basics
 * @PACKAGE_NAME:PACKAGE_NAME
 * @NAME: HttpFileDownloader
 * @author:xuandian
 * @DATE: 2022/6/25 22:42
 * @description: 下载文件
 */

public class HttpFileDownloader implements Runnable {
    private int currentPartSize;
    private RandomAccessFile currentPart;
    private CountDownLatch latch;
    private String path;


    public HttpFileDownloader(int currentPartSize, RandomAccessFile currentPart, String path, CountDownLatch latch) {
        this.currentPartSize = currentPartSize;
        this.currentPart = currentPart;
        this.path = path;
        this.latch = latch;
    }

    @Override
    public void run() {
        HttpURLConnection httpURLConnection = null;
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        File file = new File("userinfo.xml");
        try {
            URL url = new URL(path);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            bufferedInputStream = new BufferedInputStream(httpURLConnection.getInputStream());
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
            int length = currentPartSize;
            byte[] bytes = new byte[length];
            while ((length = bufferedInputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, length);
            }
            bufferedOutputStream.close();
            bufferedInputStream.close();
            httpURLConnection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert bufferedInputStream != null;
                bufferedInputStream.close();
                assert bufferedOutputStream != null;
                bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    public static void main(String[] args) {
        HttpFileDownloader httpFileDownloader = new HttpFileDownloader(2048, null, "http://58.22.61.222:57903/javasexml/user.xml", new CountDownLatch(1));
        Thread t = new Thread(httpFileDownloader);
        t.start();
    }
}
